package com.test.mchelepesa.activity_fragment_rice.loan_rice;

import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.TextView;

import androidx.core.content.ContextCompat;
import androidx.fragment.app.FragmentTransaction;

import com.test.mchelepesa.R;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseLoanActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.base_rice.BaseLoanFragment_rice;
import com.test.mchelepesa.activity_fragment_rice.fragment_rice.DataSafetyFragment_rice;
import com.test.mchelepesa.activity_fragment_rice.fragment_rice.LoanFailFragment_rice;
import com.test.mchelepesa.activity_fragment_rice.fragment_rice.LoanMainFragment_rice;
import com.test.mchelepesa.activity_fragment_rice.login_rice.VerificationActivity;
import com.test.mchelepesa.activity_fragment_rice.SettingActivity_rice;
import com.test.mchelepesa.activity_fragment_rice.fragment_rice.LoanWaitFragment_rice;
import com.test.mchelepesa.activity_fragment_rice.fragment_rice.PersonalCenterFragment_rice;
import com.test.mchelepesa.activity_fragment_rice.fragment_rice.RepayFragment_rice;
import com.test.mchelepesa.bean_rice.StaticConfig_rice;
import com.test.mchelepesa.bean_rice.config_info_rice.AppShowInfo_rice;
import com.test.mchelepesa.bean_rice.process_rice.ProcessInfo_rice;
import com.test.mchelepesa.constant_rice.Constant_rice;
import com.test.mchelepesa.dialog_rice.InitOfflinePayChannelDialog_rice;
import com.test.mchelepesa.dialog_rice.NoticeDialog_rice;
import com.test.mchelepesa.util_rice.StringUtil_rice;
import com.test.mchelepesa.util_rice.event_points.TrackManager_rice;
import com.test.mchelepesa.util_rice.helper_rice.UserInfoHelper_rice;
import com.test.mchelepesa.util_rice.http_rice.HttpManager_rice;
import com.test.mchelepesa.bean_rice.rate_rice.ActiveWindowConfig_rice;
import com.test.mchelepesa.bean_rice.rate_rice.NormalWindowConfig_rice;
import com.test.mchelepesa.dialog_rice.rate.StarActiveDialog_rice;
import com.test.mchelepesa.dialog_rice.rate.StarNormalDialog_rice;

import java.util.Objects;


public class LoanMainActivity_rice extends BaseLoanActivity_rice {

    private ViewGroup homeLayout, dataSafetyLayout, personalCenterLayout;
    private ImageView homeIv, dataSafetyIv, personalCenterIv;
    private TextView homeTv, dataSafetyTv, personalCenterTv;

    private int fragmentShow = 1;

    private BaseLoanFragment_rice homeFragment;
    private DataSafetyFragment_rice dataSafetyFragment;
    private PersonalCenterFragment_rice personalCenterFragment;

    public static boolean processFlag = false;

    public static boolean reviewNoticeFlag = true;
    public static boolean loaningNoticeFlag = true;
    public static boolean repayNoticeFlag = true;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_loan_main_rice);
        init();
    }

    private void init(){

        TrackManager_rice.INSTANCE.deleteEvents();

        homeLayout = findViewById(R.id.activity_loan_main_layout_home);
        homeIv = findViewById(R.id.activity_loan_main_iv_home);
        homeTv = findViewById(R.id.activity_loan_main_tv_home);
        dataSafetyLayout = findViewById(R.id.activity_loan_main_layout_data_safety);
        dataSafetyIv = findViewById(R.id.activity_loan_main_iv_data_safety);
        dataSafetyTv = findViewById(R.id.activity_loan_main_tv_data_safety);
        personalCenterLayout = findViewById(R.id.activity_loan_main_layout_personal_center);
        personalCenterIv = findViewById(R.id.activity_loan_main_iv_personal_center);
        personalCenterTv = findViewById(R.id.activity_loan_main_tv_personal_center);

        dataSafetyFragment = new DataSafetyFragment_rice();
        personalCenterFragment = new PersonalCenterFragment_rice(this);

        homeLayout.setOnClickListener(v -> changeToHome());
        dataSafetyLayout.setOnClickListener(v -> changeToDataSafety());
        personalCenterLayout.setOnClickListener(v -> changeToPersonalCenter());

    }

    @Override
    protected void onResume() {
        super.onResume();
        updatePage();
    }

    private void updatePage() {
        try {

            FragmentTransaction fragmentTransaction = getSupportFragmentManager().beginTransaction();

            if (homeFragment != null) fragmentTransaction.remove(homeFragment);
            if (dataSafetyFragment != null) fragmentTransaction.remove(dataSafetyFragment);
            if (personalCenterFragment != null) fragmentTransaction.remove(personalCenterFragment);

            if (ProcessInfo_rice.getInstance().isOrderPendingRepayment() || ProcessInfo_rice.getInstance().isOrderOverdueRepayment()) {//订单状态-待还款
                homeFragment = new RepayFragment_rice();
            } else if (ProcessInfo_rice.getInstance().isOrderLoaning() || ProcessInfo_rice.getInstance().isLoanReviewing()) {//订单状态-放款中/审核中
                homeFragment = new LoanWaitFragment_rice();
            } else if (ProcessInfo_rice.getInstance().isLoanRejcted()) {//订单状态-被拒绝
                homeFragment = new LoanFailFragment_rice();
                HttpManager_rice.getInstance().fetchDropConfig();
            } else {
                homeFragment = new LoanMainFragment_rice();
            }

            fragmentTransaction.add(R.id.activity_loan_main_layout_fragment, Objects.requireNonNull(homeFragment))
                    .add(R.id.activity_loan_main_layout_fragment, dataSafetyFragment)
                    .add(R.id.activity_loan_main_layout_fragment, personalCenterFragment);

            switch (fragmentShow) {
                case 2:
                    fragmentTransaction.show(dataSafetyFragment).hide(homeFragment).hide(personalCenterFragment);
                    break;
                case 3:
                    fragmentTransaction.show(personalCenterFragment).hide(homeFragment).hide(dataSafetyFragment);
                    break;
                default:
                    fragmentTransaction.show(homeFragment).hide(dataSafetyFragment).hide(personalCenterFragment);
            }

            fragmentTransaction.commitAllowingStateLoss();

        }catch (Exception e){
            StringUtil_rice.printException(e);
        }
    }

    private void changeToHome() {

        try {
            homeIv.setImageResource(R.drawable.icon_tab_home_true);
            dataSafetyIv.setImageResource(R.drawable.icon_tab_data_safety_false);
            personalCenterIv.setImageResource(R.drawable.icon_tab_personal_center_false);

            homeTv.setTextColor(ContextCompat.getColor(this,R.color.orange_rice));
            dataSafetyTv.setTextColor(ContextCompat.getColor(this,R.color.gray_dd));
            personalCenterTv.setTextColor(ContextCompat.getColor(this,R.color.gray_dd));

            getSupportFragmentManager().beginTransaction().show(homeFragment).hide(dataSafetyFragment).hide(personalCenterFragment).commitAllowingStateLoss();
        }catch (Exception e){
            StringUtil_rice.printException(e);
        }

        fragmentShow = 1;
    }

    private void changeToDataSafety() {

        try {
            homeIv.setImageResource(R.drawable.icon_tab_home_false);
            dataSafetyIv.setImageResource(R.drawable.icon_tab_data_safety_true);
            personalCenterIv.setImageResource(R.drawable.icon_tab_personal_center_false);

            homeTv.setTextColor(ContextCompat.getColor(this,R.color.gray_dd));
            dataSafetyTv.setTextColor(ContextCompat.getColor(this,R.color.orange_rice));
            personalCenterTv.setTextColor(ContextCompat.getColor(this,R.color.gray_dd));

            getSupportFragmentManager().beginTransaction().show(dataSafetyFragment).hide(homeFragment).hide(personalCenterFragment).commitAllowingStateLoss();
        }catch (Exception e){
            StringUtil_rice.printException(e);
        }

        fragmentShow = 2;
    }

    private void changeToPersonalCenter() {

        try {
            homeIv.setImageResource(R.drawable.icon_tab_home_false);
            dataSafetyIv.setImageResource(R.drawable.icon_tab_data_safety_false);
            personalCenterIv.setImageResource(R.drawable.icon_tab_personal_center_true);

            homeTv.setTextColor(ContextCompat.getColor(this,R.color.gray_dd));
            dataSafetyTv.setTextColor(ContextCompat.getColor(this,R.color.gray_dd));
            personalCenterTv.setTextColor(ContextCompat.getColor(this,R.color.orange_rice));

            getSupportFragmentManager().beginTransaction().show(personalCenterFragment).hide(homeFragment).hide(dataSafetyFragment).commitAllowingStateLoss();
        }catch (Exception e){
            StringUtil_rice.printException(e);
        }

        fragmentShow = 3;
    }

    //配置信息返回响应
    public void onAppShowInfoResponse() {
        if (personalCenterFragment != null) personalCenterFragment.updateCustomerService();
    }

    //额度列表返回响应
    public void onLoanLimitInfoResponse() {
        if (homeFragment != null && homeFragment instanceof LoanMainFragment_rice)
            ((LoanMainFragment_rice) homeFragment).updateLoanAmount_rice();
    }

    @Override
    public void onUserProcessResponse_rice() {

        if (ProcessInfo_rice.getInstance().isNeedVerification()){
            UserInfoHelper_rice.getInstance().setVerificationFlag(Constant_rice.VerificationFlag_HOME);
            startActivityForSingleTop_rice(VerificationActivity.class);
            return;
        }

        //订单状态-待还款
        if (ProcessInfo_rice.getInstance().isOrderPendingRepayment() || ProcessInfo_rice.getInstance().isOrderOverdueRepayment()) {
            if (homeFragment instanceof RepayFragment_rice) {
                HttpManager_rice.getInstance().getRepayDetail();
            } else updatePage();
            return;
        }
        //订单状态-审核中/放款中
        if (ProcessInfo_rice.getInstance().isLoanReviewing() || ProcessInfo_rice.getInstance().isOrderLoaning()) {
            if (!(homeFragment instanceof LoanWaitFragment_rice)) updatePage();
            return;
        }
        //订单状态-被拒绝
        if (ProcessInfo_rice.getInstance().isLoanRejcted()) {
            if (!(homeFragment instanceof LoanFailFragment_rice)) updatePage();
            return;
        }
        //其他订单状态
        if (homeFragment instanceof LoanMainFragment_rice) {
            if (processFlag){
                processFlag = false;
                startLoanProcess();
            }else HttpManager_rice.getInstance().queryLoanLimit();
        } else updatePage();

    }

    public void onLoanApplyDetailResponse() {

        //订单状态-放款中/审核中
        if (ProcessInfo_rice.getInstance().isOrderLoaning() || ProcessInfo_rice.getInstance().isLoanReviewing()) {
            if ((homeFragment instanceof LoanWaitFragment_rice)) ((LoanWaitFragment_rice) homeFragment).onLoanApplyDetailResponse();
        }else startActivity_rice(LoanApplyActivity_rice.class);
    }

    public void onRepayDetailResponse() {
        if (homeFragment != null && homeFragment instanceof RepayFragment_rice)
            ((RepayFragment_rice) homeFragment).updateRepayDetail();
    }

    public void onOrderRepayH5Response(String url) {
        if (homeFragment != null && homeFragment instanceof RepayFragment_rice) {
            Uri uri = Uri.parse(StringUtil_rice.getSafeString(url));
            Intent intent = new Intent(Intent.ACTION_VIEW, uri);
            startActivity(intent);
        }
    }

    //获取bankAccountList返回(科特)
    public void onFetchBankAccountListResponse(){
        //更新科特放款卡列表
        if (homeFragment!=null && homeFragment instanceof LoanWaitFragment_rice) ((LoanWaitFragment_rice) homeFragment).updateSpecialAccounts();
    }

    //获取bankAccountList返回(尼日)
    public void onFetchBankListResponse_Niri(){
        //订单状态-还款中
        if (StaticConfig_rice.Select_Country.equalsIgnoreCase(Constant_rice.Country_Nigeria)&&
                (ProcessInfo_rice.getInstance().isOrderPendingRepayment() || ProcessInfo_rice.getInstance().isOrderOverdueRepayment())) {
            if (homeFragment instanceof RepayFragment_rice) ((RepayFragment_rice) homeFragment).onFetchBankListResponse_Niri();
        }
    }

    //获取线下还款通道响应-尼日
    public void onInitOfflinePayChannelResponse() {
        InitOfflinePayChannelDialog_rice.showDialog(this, dialogInterface -> HttpManager_rice.getInstance().getRepayDetail());
    }

    public void onStarWindowConfigResponse(){
        if (homeFragment!=null){
            //评分弹窗显示流程
            //1.活动弹窗
            if (ActiveWindowConfig_rice.getInstance_pretfacile().isSwitch() &&
                    UserInfoHelper_rice.getInstance().getStarActiveCount_rice()< ActiveWindowConfig_rice.getInstance_pretfacile().getNum()){
                new StarActiveDialog_rice(this).show();
                return;
            }

            //2.评价弹窗
            if (NormalWindowConfig_rice.getInstance_pretfacile().isSwitch() &&
                    UserInfoHelper_rice.getInstance().getStarNormalCount_rice()< NormalWindowConfig_rice.getInstance_pretfacile().getNum()){
                new StarNormalDialog_rice(this).show();
                return;
            }

            //3.公告
            if (ProcessInfo_rice.getInstance().isOrderLoaning()){
                String notice = AppShowInfo_rice.getInstance().getLoaningNotice();
                if (loaningNoticeFlag && !TextUtils.isEmpty(notice)){
                    loaningNoticeFlag = false;
                    new NoticeDialog_rice(this,notice).show();
                }
            }else {
                String notice = AppShowInfo_rice.getInstance().getReviewNotice();
                if (reviewNoticeFlag && !TextUtils.isEmpty(notice)){
                    reviewNoticeFlag = false;
                    new NoticeDialog_rice(this,notice).show();
                }
            }

        }
    }

    public void onAddAccountResponse(boolean addBindFlag,String channel){
        if (homeFragment!=null && homeFragment instanceof LoanWaitFragment_rice){
            LoanWaitFragment_rice loanWaitFragment = (LoanWaitFragment_rice) homeFragment;
            loanWaitFragment.addBindFlag = addBindFlag;
            loanWaitFragment.bindAccountNewChannel = channel;
            HttpManager_rice.getInstance().fetchBankAccount();
        }
    }

    public void onDeleteAccountResponse(){
        HttpManager_rice.getInstance().fetchBankAccount();
    }

    public void onDropConfigResponse(){

        if (personalCenterFragment!=null && personalCenterFragment.toSettingFlag){
            personalCenterFragment.toSettingFlag = false;
            startActivity_rice(SettingActivity_rice.class);
            return;
        }

        if (homeFragment!=null && homeFragment instanceof LoanFailFragment_rice){
            ((LoanFailFragment_rice) homeFragment).onDropConfigResponse();
        }

    }

    public boolean isRepayOverdue(){
        return homeFragment instanceof RepayFragment_rice repayFragment && repayFragment.isOverdue;
    }


}